import { createSlice,createAsyncThunk,createSelector,createEntityAdapter } from "@reduxjs/toolkit";
import { nanoid } from "@reduxjs/toolkit";
import { client } from "../../api/client";
//import { sub } from "date-fns";

// const data = [
//   { 
//     id: "1",
//     userId: 1001,
//     title: "First Post!",
//     content: "Hello!",
//     date: sub(new Date(), { minutes: 10 }).toISOString(),
//     reactions: {
//       thumbsUp: 0,
//       hooray: 0,
//       heart: 0,
//       rocket: 0,
//       eyes: 0
//     }
//   },
//   { 
//     id: "2",
//     userId: 1002,
//     title: "Second Post",
//     content: "More text",
//     date: sub(new Date(), { minutes: 5 }).toISOString(),
//     reactions: {
//       thumbsUp: 0,
//       hooray: 0,
//       heart: 0,
//       rocket: 0,
//       eyes: 0
//     }
//   },
// ];

// const initialState = {
//   items: [],
//   status: "idle",
//   error: null
// }

// 用createEntityAdapter创建postsAdapter对象
// 我们希望保留一个所有帖子ID并按最新排序的数组
// 所以我们传入一个sortComparer函数，它将根据post.date字段将较新的项排序到前面。

const postsAdapter = createEntityAdapter({
  sortComparer: (a,b) => b.date.localeCompare(a.date) 
})

//console.log('postsAdapter',postsAdapter)

// getInitialState()返回一个空的{ ids: [],entities: {}} 范式化state对象
const initialState = postsAdapter.getInitialState({
  status: 'idle',
  error: null
})

//console.log('initialState',initialState)

export const addNewPost = createAsyncThunk(
  'posts/addNewPost',
  async (initialPost) => {
    const response = await client.post('/fakeApi/posts', initialPost)
    return response.data
  }
)

// const fetchData = () => {
//   return new Promise((resolve) => {
//     setTimeout(() => resolve(data), 2000);
//   });
// }

export const fetchPosts = createAsyncThunk("posts/fetchPosts",async () => {
  const response = await client.get("/fakeApi/posts");
  return response.data;

  //return await fetchData();
})

// export const fetchPosts = () => {
//   return async () => {
//     const response = await client.get("/fakeApi/posts");
//     return response.data;
//   }
// }

const postsSlice = createSlice({
    name: "posts",
    initialState,
    reducers: {
        // postAdded(state,action) {
        //   console.log('action---',action)
        //   state.push(action.payload)
        // },
        postAdded: {
            reducer(state,action) {
              state.items.push(action.payload)
            },
            prepare(title,content,userId) {
              return {
                payload: {
                  id: nanoid(),
                  date: new Date().toISOString(),
                  title,
                  content,
                  userId,
                }
              }
            }
        },
        postUpdated(state, action) {
          const { id, title, content } = action.payload;
          const existingPost = state.items.find((post) => post.id === id);
          if (existingPost) {
            existingPost.title = title;
            existingPost.content = content;
          }
        },
        reactionAdded(state, action) {
          const { postId, reaction } = action.payload;
          const existingPost = state.items.find((post) => post.id === postId);
          if (existingPost) {
            existingPost.reactions[reaction]++;
          }
        },
    },
    extraReducers(builder) {
      builder
        .addCase(fetchPosts.pending, (state, action) => {
          state.status = 'loading'
        })
        .addCase(fetchPosts.fulfilled, (state, action) => {
          state.status = 'succeeded'
          // Add any fetched posts to the array
          //console.log('action.payload',action.payload)
          //state.items = state.items.concat(action.payload)

          postsAdapter.upsertMany(state,action.payload)
        })
        .addCase(fetchPosts.rejected, (state, action) => {
          state.status = 'failed'
          state.error = action.error.message
        })
        .addCase(addNewPost.fulfilled, (state, action) => {
          //state.items.push(action.payload)
          postsAdapter.addOne(state,action.payload)
        })
    },
})

export const { postAdded,postUpdated,reactionAdded } = postsSlice.actions;

//export const selectAllPosts = (state) => state.posts.items;

//export const selectPostById = (state, postId) => state.posts.items.find((post) => post.id === postId);

// postsAdapter.getSelectors生成的selector函数替换旧的手写selectAllPosts和selectPostById selector函数。

export const {
  selectAll: selectAllPosts,
  selectById: selectPostById,
  selectIds: selectPostIds
} = postsAdapter.getSelectors(state => state.posts)


export const selectPostsByUser = createSelector(
  [selectAllPosts, (state, userId) => userId],
  (posts, userId) => posts.filter((post) => post.user === userId)
);

//console.log('postsSlice',postsSlice)

export default postsSlice.reducer;